package cn.com.captureNetPacket.util;

import java.io.UnsupportedEncodingException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;

import com.fasterxml.jackson.databind.ObjectMapper;

import cn.com.captureNetPacket.CaptureNetPacketService;
import cn.com.captureNetPacket.StartApplication;
import cn.com.captureNetPacket.model.DeviceStatus;
import cn.com.captureNetPacket.model.RecordLog;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

@Slf4j
public class RedisMessageListener implements MessageListener{
	private ObjectMapper objMapper=new ObjectMapper();
	@Override
	public void onMessage(Message message, byte[] pattern) {
		String patternString="";
		 try {
			 if(pattern!=null)
			  patternString=new String(pattern,"UTF-8");
			 
		} catch (UnsupportedEncodingException e) {
			log.error("RedisLeaderMessageListener ",e);
		} 
		 DeviceStatus deviceStatus=null;Map <String,Object> payload=null;
		 try {
		 log.info("收到RedisLeaderMessageListener 订阅消息：{}  patternString:{}", message,patternString);
		 Map <String,Object> mesSta=JsonPathUtil.getValue(message.toString(), "$",Map.class);
		String messType= mesSta.get("messType").toString();
		  payload=(Map<String, Object>) mesSta.get("payload");
		  if(messType.equals("recLog")){
//			 if(CaptureNetPacketService.appId==1)
//				 return;
			 // 处理录音的队列
			 List<Object> reclogs= RedisConfig.subRecQueueMessage("recLog");
			 
			 log.debug("RecordLog---->>>:---------->:收到 {} 条记录,详细信息: {}",reclogs.size(),objMapper.writeValueAsString(reclogs) );
			 for (Object object : reclogs) {
				 log.debug("RecordLog:---------->: 正在入库的记录。 {}  类型: {}",objMapper.writeValueAsString(object),object.getClass() );
				 try {
				 RecordLog RecordLog= JsonPathUtil.getValue(objMapper.writeValueAsString(object) , "$",RecordLog.class);
				 if(!StringUtils.hasText(RecordLog.getId())){
					 log.warn("RecordLog:---------->: 垃圾数据。 {}",objMapper.writeValueAsString(object) );
                  continue;
				 }

					 RecordLog.setBeginTime(RecordLog.getBeginTimeString());
					 RecordLog.setEstablishTime(RecordLog.getEstablishTimeString());
					 RecordLog.setEndTime(RecordLog.getEndTimeString());
					 RecordLog.setRingTime(RecordLog.getRingTimeString());
				 CaptureNetPacketService.getRecLogMapper().addRecordLog(RecordLog);
				 }catch (Exception e) {
					 log.error("RecordLog: 错误的录音记录。 {}    add error", objMapper.writeValueAsString(object) ,e);
				}
			}
			 
			 
		 }
		 
		  
		 
		 }catch (Exception e) {
			 log.error("RedisLeaderMessageListener {}",payload,e);
		}
	}

}
